﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using BCCommon;
using BCEntity.OA.WorkflowTemplate.WorkflowCategory;

namespace BCData.OA.WorkflowTemplate.WorkflowCategory
{
    public class WorkflowCategoryData : IWorkflowCategoryData
    {
        private const string QUERY_EXISTS = @"SELECT 1 FROM oa_workflowcategory";
        private const string QUERY = @"SELECT WorkflowCategoryId,EditAdminName,UpdateTime,CategoryCode,CategoryName,IsPredefined,CompanyId,CreateAdminId,CreateAdminName,CreateTime,EditAdminId FROM oa_workflowcategory";

        private readonly IDatabaseContext databaseContext;

        public WorkflowCategoryData(IDatabaseContext databaseContext)
        {
            this.databaseContext=databaseContext;
        }
        public async Task<bool> Exists(string categoryName)
        {
            string sql = string.Format(@"{0} WHERE CompanyId IS NULL AND CategoryName=?CategoryName;", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?CategoryName", categoryName, DbType.AnsiString, size: 30);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }

        public async Task<bool> Exists(long companyId, string categoryName)
        {
            string sql = string.Format(@"{0} WHERE CompanyId=?CompanyId AND CategoryName=?CategoryName;", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?CompanyId", companyId, DbType.Int64);
            parameters.Add("?CategoryName", categoryName, DbType.AnsiString, size: 30);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }

        public async Task<bool> Exists(long WorkflowCategoryId)
        {
            string sql = string.Format(@"{0} WHERE WorkflowCategoryId = ?WorkflowCategoryId;", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkflowCategoryId", WorkflowCategoryId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;

        }

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public async Task<WorkflowCategoryEntity> Add(WorkflowCategoryEntity entity)
        {

            string sql = SqlCommands.GetInsertSql("oa_workflowcategory", new string[] { "CategoryCode", "CategoryName", "IsPredefined", "CompanyId", "CreateAdminId", "CreateAdminName" });
            sql = string.Format("{0} {1} WHERE WorkflowCategoryId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?CategoryCode", entity.CategoryCode?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?CategoryName", entity.CategoryName?.Trim(), DbType.AnsiString, size: 30);
            parameters.Add("?IsPredefined", entity.IsPredefined, DbType.Boolean);
            parameters.Add("?CompanyId", entity.CompanyId, DbType.Int32, size: 11);
            parameters.Add("?CreateAdminId", entity.CreateAdminId, DbType.Int64, size: 20);
            parameters.Add("?CreateAdminName", entity.CreateAdminName?.Trim(), DbType.AnsiString, size: 20);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<WorkflowCategoryEntity>(sql, parameters, databaseContext.Transaction);

        }

        public async Task<WorkflowCategoryEntity> Update(WorkflowCategoryEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("oa_workflowcategory", new string[] { "EditAdminName", "CategoryCode", "CategoryName", "IsPredefined", "CompanyId", "EditAdminId" }, new string[] { "WorkflowCategoryId" });
            sql = string.Format("{0} {1} WHERE WorkflowCategoryId=?WorkflowCategoryId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkflowCategoryId", entity.WorkflowCategoryId, DbType.Int64, size: 20);
            parameters.Add("?EditAdminName", entity.EditAdminName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?CategoryCode", entity.CategoryCode?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?CategoryName", entity.CategoryName?.Trim(), DbType.AnsiString, size: 30);
            parameters.Add("?IsPredefined", entity.IsPredefined, DbType.Boolean);
            parameters.Add("?CompanyId", entity.CompanyId, DbType.Int32, size: 11);
            parameters.Add("?EditAdminId", entity.EditAdminId, DbType.Int64, size: 20);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<WorkflowCategoryEntity>(sql, parameters, databaseContext.Transaction);
        }

        public async Task<bool> Delete(long workflowCategoryId)
        {
            string sql = @"DELETE FROM oa_workflowcategory WHERE WorkflowCategoryId=?WorkflowCategoryId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkflowCategoryId", workflowCategoryId);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }

        public async Task<WorkflowCategoryEntity> GetEntity(long workflowCategoryId)
        {
            string sql = string.Format("{0} WHERE WorkflowCategoryId=?WorkflowCategoryId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkflowCategoryId", workflowCategoryId);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<WorkflowCategoryEntity>(sql, parameters);
        }
        public async Task<WorkflowCategoryEntity> GetEntity(string categoryCode)
        {
            string sql = string.Format("{0} WHERE CategoryCode=?CategoryCode", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?CategoryCode", categoryCode);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<WorkflowCategoryEntity>(sql, parameters);
        }

        public async Task<IEnumerable<WorkflowCategoryEntity>> GetList(int? companyId)
        {
            if (companyId.HasValue)
            {
                string sql = string.Format("{0} WHERE CompanyId=?CompanyId", QUERY);
                DynamicParameters parameters = new DynamicParameters();
                parameters.Add("?CompanyId", companyId, DbType.Int32, size: 11);
                return await this.databaseContext.Slave.QueryAsync<WorkflowCategoryEntity>(sql, parameters);
            }
            else
            {
                return await this.databaseContext.Slave.QueryAsync<WorkflowCategoryEntity>(QUERY);
            }
        }

        public async Task<(IEnumerable<WorkflowCategoryEntity>, int)> Query(int? companyId, string categoryName, DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (companyId.HasValue)
            {
                wheres.Add("CompanyId=?CompanyId");
                parameters.Add("?CompanyId", companyId, DbType.Int32, size: 11);
            }
            if (!string.IsNullOrWhiteSpace(categoryName))
            {
                wheres.Add("CategoryName LIKE CONCAT('%',CONCAT(?CategoryName,'%'))");
                parameters.Add("?CategoryName", categoryName, DbType.AnsiString);
            }
            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY {4} {5} LIMIT {2},{3}; SELECT COUNT(1) FROM oa_workflowcategory {1}",
                  QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                  pageSize,
                  string.IsNullOrWhiteSpace(sortName) ? "CreateTime" : sortName,
                  ascending.HasValue && ascending.Value ? "ASC" : "DESC");
            return await this.databaseContext.Slave.QueryMultipleAsync<WorkflowCategoryEntity, int>(sql, parameters);
        }

    }
}
